// formPackage/pages/article/richArticlePage/richArticlePage.js
let WxParse = require('../../../sdk/wxParse/wxParse');
import { queryRichArticleDetail } from "../../../../service/article_service"
import { loginWxAction, queryPersonInfoByOpenId } from "../../../../service/config"
import { bindUserRelation } from "../../../../service/user_service"
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    richText: "",
    detailId: "",
    title: "",
    isShare: false,
    icon: "",
    iconName: "",
    publishTimeAt: "",
    roleType: 1,
    requestOpenId: "",
    bindUserId: "",
    showExpert: false,
    expertData: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      detailId: options.id,
      roleType: app.globalData.roleType || 1,
    })
    if (options.isShare == 1) {
      this.setData({
        isShare: true,
        requestOpenId: options.openId || "",
        bindUserId: options.userId
      })
      this.userWxLogin();
    }
    this.queryRichArticleDetail();
  },
  queryRichArticleDetail() {
    wx.showLoading();
    queryRichArticleDetail(this.data.detailId).then(res => {
      wx.hideLoading();
      console.log("JJLog:详情是:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          richText: res.data.richContent || "",
          title: res.data.title || "",
          icon: res.data.icon || "",
          iconName: res.data.iconName || "",
          publishTimeAt: res.data.createdAt
        })
        WxParse.wxParse('article', 'html', this.data.richText, this);
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || '查询失败',
        icon: "none"
      })
      console.error("JJLog:queryRichArticleDetail", err);
    })
  },
  //用户登陆授权等:
  userWxLogin() {
    loginWxAction().then((res => {
      console.log("JJLog:登录返回:" + JSON.stringify(res));
      let data = res.data.data;
      if (res.code == 200) {
        app.globalData.nickName = data.nickName;
        app.globalData.avatar = data.avatar;
        app.globalData.name = data.name || "";
        app.globalData.phone = data.phone || "";
        app.globalData.isLogin = data.isLogin;
        app.globalData.userId = data.id;
        app.globalData.qrCode = data.qrCode || "";
        app.globalData.isAuthUserInfo = data.isAuthUserInfo;
        app.globalData.weChat = data.weChat || "";
        app.globalData.roleName = data.roleName || "";
        app.globalData.companyName = data.companyName || "";
        app.globalData.companyNumber = data.companyNumber || "";
        app.globalData.isBindMp = data.isBindMp;
        app.globalData.roleType = data.roleType || 1

        //绑定挂级关系:
        if (this.data.bindUserId) {
          this.bindUserRelation();
        }
        if (this.data.requestOpenId) {
          this.queryPersonInfoByOpenId();
        }



        this.loginTIMAction(data.openId, res.data.userSig);


      }
    })).catch(err => {
      console.error("JJLog:userWxLogin", err);

    })
  },
  //登录TIM===============:
  loginTIMAction(userId, userSig) {
    let promise = app.globalData.tim.login({ userID: userId, userSig: userSig });
    promise.then(function (imResponse) {
      console.log("JJLog:登录tim成功:" + JSON.stringify(imResponse.data)); // 登录成功
      if (imResponse.data.repeatLogin === true) {
        // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
        console.log(imResponse.data.errorInfo);
      }
    }).catch(function (imError) {
      console.error('JJLog登录腾讯TIM失败===:', imError); // 登录失败的相关信息
    });
  },

  //绑定挂级关系:
  bindUserRelation() {
    let type = 2;

    bindUserRelation(type, this.data.bindUserId).then(res => {
      console.log("JJLog:绑定挂级关系:" + JSON.stringify(res));

    }).catch(err => {
      console.error("JJLog:bindUserRelation:", err);
    })
  },
  //查询个人详情:
  queryPersonInfoByOpenId() {
    queryPersonInfoByOpenId(this.data.requestOpenId).then(res => {
      console.log("JJLog:查询到的详情是:" + JSON.stringify(res));
      if (res.code == 200) {
        if (res.data && res.data.avatar) {
          this.setData({
            showExpert: true,
            expertData: res.data
          })
        }
      }
    }).catch(err => {
      console.error("JJLog:queryPersonInfoByOpenId", err);
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  backHomeAction() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },

  //拨打电话
  callPhoneAction() {
    let phone = this.data.expertData.phone
    wx.makePhoneCall({
      phoneNumber: phone,
      fail: err => {

      }
    })
  },
  //聊天咨询:
  chatAction() {
    let data = this.data.expertData;
    let chatData = {
      name: data.nickName || "聊天",
      avatar: data.avatar,
      chatUserId: data.openId,
      conversationType: "C2C",
    }
    app.globalData.chatData = chatData;
    wx.navigateTo({
      url: '/firstPackage/pages/msgModule/chatRoom/chatRoom',
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let title = "";
    if (this.data.title) {
      title = this.data.title;
    } else {
      title = app.globalData.commonShareTitle;
    }
    let openId = "";
    let userId = "";
    if (this.data.roleType == 7 || this.data.roleType == 9) {
      openId = app.globalData.openId;
      userId = app.globalData.userId
    }
    return {
      title: title,
      path: "/formPackage/pages/article/richArticlePage/richArticlePage?isShare=1" + "&id=" + this.data.detailId + "&openId=" + openId + "&userId=" + userId
    }
  }
})